#pragma once

#include <iostream>
#include <string>
#include "Log.hpp"
#include "LockGuard.hpp"
#include <cstdio>
#include <set>

const std::string sep = " ";

class Command
{
private:
    // 加载配置文件
    void LoadConf()
    {
        std::ifstream in(_cond_path);
        if (!in.is_open())
        {
            LOG(FATAL, "open %s error\n", _cond_path.c_str());
            return;
        }
        std::string line;
        while (std::getline(in, line))
        {
            LOG(DEBUG, "Load Command [%s] success\n", line.c_str());
            _safe_cmd.insert(line);
        }
        in.close();
    }
    std::string PrefixCmd(std::string &cmd)
    {
        if (cmd.empty())
            return std::string();
        auto pos = cmd.find(sep);
        if (pos == std::string::npos)
            return cmd;
        else
            return cmd.substr(0, pos);
    }
    bool CheckSafe(std::string cmd)
    {
        std::string prefix = PrefixCmd(cmd);
        auto iter = _safe_cmd.find(prefix);
        if (iter == _safe_cmd.end())
            return false;
        return true;
    }

public:
    Command(const std::string &cond_path)
        : _cond_path(cond_path)
    {
        LoadConf();
    }
    // 回调业务模块Excute  --- 给命令返回命令执行结果
    std::string Excute(const std::string &cmd)
    {
        std::string result;
        // 安全检查，命令安全执行
        if (CheckSafe(cmd))
        {
            FILE *fp = popen(cmd.c_str(), "r");
            if (fp == nullptr)
            {
                LOG(ERROR, "popen error\n");
                return "error";
            }
            char buffer[1024];
            while (std::fgets(buffer, sizeof(buffer), fp) != nullptr)
            {
                result += buffer;
            }
            pclose(fp);
        }
        else
        {
            result = "小黑子";
        }
        return result;
    }

private:
    std::set<std::string> _safe_cmd;
    std::string _cond_path;
};